//
//  SearchBarVC.m
//  CarHome
//
//  Created by 蒋寒霄 on 14-9-23.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "SearchBarVC.h"
//CustomView
#import "SearchDetail.h"
#import "SearchDetailWebVC.h"
//CustomCollectionCell
#import "HistoryCollectionCell.h"
//VC
#import "DetailedViewController.h"
//cell重用
NSString *const cell_Search = @"searchBarCell";
NSString *const historyCollectionCell = @"historyCollectionCell";
@interface SearchBarVC ()<UISearchBarDelegate, UISearchDisplayDelegate,UITableViewDataSource, UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
{
    UISearchBar *_searchAll;
    UISearchDisplayController * _searchDisplay;
    
    NSMutableArray *_arrData;
    //collectionHistory
    NSMutableArray *_collectionArr;
}
@property (nonatomic, retain) UICollectionView *historyCollection;
@end

@implementation SearchBarVC

- (void)dealloc
{
    [_arrData release];
    _arrData = nil;
    [_collectionArr release];
    _collectionArr = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _arrData = [[NSMutableArray alloc] init];
        //
        NSString *paths = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
        paths = [NSString stringWithFormat:@"%@/%@", paths, @"doubi.txt"];
        _collectionArr = [[NSMutableArray alloc] init];
        [_collectionArr addObjectsFromArray:[NSArray arrayWithContentsOfFile:paths]];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = myColor_dark;
    
    UIImageView *backGround = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SearchBackground.png"]];
    [backGround setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    
    [self.view addSubview:backGround];
    [backGround release];
    
    [self createSearchBar];
    [self createLabelWithHistory];
    [self createHistroyCollectionView];
}
#pragma mark -
#pragma mark createHistory
- (void)createLabelWithHistory
{
    UILabel *historyName = [[UILabel alloc] initWithFrame:CGRectMake(20, 80, 100, 30)];
    historyName.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.9];
    historyName.text = @"历史记录";
    historyName.textAlignment = NSTextAlignmentCenter;
    historyName.layer.cornerRadius = 10;
    historyName.clipsToBounds = YES;
    historyName.font = [UIFont systemFontOfSize:20];
    historyName.textColor = [UIColor whiteColor];
    [self.view addSubview: historyName];
    [historyName release];
}
#pragma mark createHistroyCollectionView
- (void)createHistroyCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 5;//水平
    layout.minimumLineSpacing = 5;
    
    _historyCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(20, 120, 280, self.view.frame.size.height - 168) collectionViewLayout:layout];
    _historyCollection.delegate = self;
    _historyCollection.dataSource = self;
    _historyCollection.backgroundColor = [UIColor colorWithWhite:1 alpha:0.6];
    _historyCollection.layer.cornerRadius = 10;
    _historyCollection.clipsToBounds = YES;
    [_historyCollection registerClass:[HistoryCollectionCell class] forCellWithReuseIdentifier:historyCollectionCell];
    _historyCollection.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);//设置collectionView的边缘距离
    [self.view addSubview:_historyCollection];
    [_historyCollection release];
}

#pragma mark createSearchBar
- (void)createSearchBar
{
    _searchAll = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 50)];
    _searchAll.placeholder = @"输入关键字";
    _searchAll.showsCancelButton = YES;
    _searchAll.delegate = self;
    [_searchAll setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_searchAll];
    _searchAll.showsBookmarkButton = YES;
    _searchAll.showsSearchResultsButton = YES;
    [_searchAll setImage:[UIImage imageNamed:@"search_button_triangle.png"] forSearchBarIcon:UISearchBarIconResultsList state:UIControlStateNormal];
    [_searchAll release];
    
    _searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:_searchAll contentsController:self];
    _searchDisplay.delegate = self;
    _searchDisplay.searchResultsDataSource = self;
    _searchDisplay.searchResultsDelegate = self;
    [_searchDisplay.searchResultsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cell_Search];
    
}

#pragma mark -
#pragma mark searchBarDelegate
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    paths = [NSString stringWithFormat:@"%@/%@", paths, @"doubi.txt"];
    [_collectionArr writeToFile:paths atomically:YES];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchAll resignFirstResponder];
}
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    controller.searchBar.showsCancelButton = YES;
    NSString *strURL = [NSString stringWithFormat:SearchURL, controller.searchBar.text];
    [NetUrl connect:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSDictionary *dic = [dictionary objectForKey:@"result"];
        NSMutableArray *wordListArr = [dic objectForKey:@"wordlist"];
        [_arrData removeAllObjects];
        [_arrData addObjectsFromArray:wordListArr];
        [_searchDisplay.searchResultsTableView reloadData];
    }];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    if (searchBar.text.length != 0) {
        for (NSString *str in _collectionArr) {
            if ([str isEqualToString:searchBar.text]) {
                return;
            }
        }
        [_collectionArr addObject:searchBar.text];
    }
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSString *strURL = [NSString stringWithFormat:SearchURL, searchText];
    [NetUrl connect:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSDictionary *dic = [dictionary objectForKey:@"result"];
        NSMutableArray *wordListArr = [dic objectForKey:@"wordlist"];
        [_arrData removeAllObjects];
        [_arrData addObjectsFromArray:wordListArr];
        [_searchDisplay.searchResultsTableView reloadData];
    }];
}
#pragma mark searchDisplayControllerDelegate
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    
    return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    return YES;
}
#pragma mark -
#pragma mark tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_arrData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_Search];
    cell.textLabel.text = [[_arrData objectAtIndex:indexPath.row] objectForKey:@"name"];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchAll resignFirstResponder];
    NSString * searchName = [[_arrData objectAtIndex:indexPath.row] objectForKey:@"name"];
    NSString *strURL = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.2/sou/search.ashx?a=2&pm=1&v=4.2.0&q=%@&p=1&s=20&c=110100&cn=北京", searchName];
    [NetUrl connect:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parmater:nil Block:^(NSData *data) {
        NSDictionary * dictionary= (NSDictionary *)data;
        NSDictionary *result = [dictionary objectForKey:@"result"];
        SearchDetail *searchView = [[SearchDetail alloc] initWithFrame:CGRectMake(0, 60, 320, 518)];
        [searchView setResultDictionary:result url:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        ///section= 3时,进网页
        SearchDetailWebVC *webVC = [[SearchDetailWebVC alloc] init];
        [searchView setSearchDetailBlock:^(NSString *urlStr) {
            [self presentViewController:webVC animated:YES completion:^{
            }];
            [webVC setWebUrl:urlStr];
        }];
        ///section = 1或者2时,进DetailedViewController.h
        DetailedViewController *detailVC = [[DetailedViewController alloc] init];
        [searchView setSearchStyleBlock:^(NSString *cardId, NSString *specitem, NSString *title) {
            [self presentViewController:detailVC animated:YES completion:^{
            }];
            [detailVC setConnect:cardId AndSpe:specitem Andtitle:title];
        }];
        [self.view addSubview:searchView];
        [webVC release];
        [searchView release];
    }];
}
#pragma mark -
#pragma mark CollectionDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_collectionArr count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HistoryCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:historyCollectionCell forIndexPath:indexPath];
    cell.layer.cornerRadius = 5;
    cell.clipsToBounds = YES;
    cell.historytext.text = [_collectionArr objectAtIndex:indexPath.item];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    [_collectionArr removeObjectAtIndex:indexPath.item];
    [_searchDisplay setActive:YES animated:YES];
    [_searchAll becomeFirstResponder];
    _searchAll.text = [_collectionArr objectAtIndex:indexPath.item];
    NSString *strURL = [NSString stringWithFormat:SearchURL, _searchAll.text];
    [NetUrl connect:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSDictionary *dic = [dictionary objectForKey:@"result"];
        NSMutableArray *wordListArr = [dic objectForKey:@"wordlist"];
        [_arrData removeAllObjects];
        [_arrData addObjectsFromArray:wordListArr];
        [_searchDisplay.searchResultsTableView reloadData];
    }];

}
#pragma mark CollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return  CGSizeMake(50, 25);
}
#pragma mark -
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
